<template>
  <div class="video-detail">
    <h2>课程视频管理</h2>
    <p>当前课程ID：{{ courseId }}</p>

    <!-- 视频列表 -->
    <div class="video-list">
      <div class="list-header">
        <h3>视频列表</h3>
        <el-button type="primary" @click="showUploadDialog">上传新视频</el-button>
      </div>
      
      <el-table :data="videoList" v-loading="loading" border style="width: 100%">
        <el-table-column prop="title" label="标题" min-width="150" />
        <el-table-column prop="content" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="视频预览" width="200">
          <template #default="scope">
            <video 
              :src="getVideoUrl(scope.row.video)" 
              controls 
              style="width: 180px; height: 100px;"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 上传/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="描述" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入视频描述"
          />
        </el-form-item>
        <el-form-item label="视频文件" prop="file">
          <el-upload
            class="upload-demo"
            :show-file-list="true"
            :auto-upload="false"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept="video/*"
          >
            <el-button type="primary">选择视频</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="uploading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  uploadVideoService, 
  getVideoListService, 
  updateVideoService, 
  deleteVideoService 
} from '@/apis/video'

const route = useRoute()
const courseId = route.params.courseId

const videoList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('上传新视频')
const uploading = ref(false)
const formRef = ref(null)

const form = ref({
  videoId: null,
  title: '',
  content: '',
  file: null
})

const fileList = ref([])

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  file: [{ required: true, message: '请上传视频文件', trigger: 'change' }]
}

// 获取视频列表
const getVideoList = async () => {
  loading.value = true
  try {
    const res = await getVideoListService(courseId)
    if (res.code === 1000) {
      videoList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取视频列表失败')
  } finally {
    loading.value = false
  }
}

// 显示上传对话框
const showUploadDialog = () => {
  dialogTitle.value = '上传新视频'
  form.value = {
    videoId: null,
    title: '',
    content: '',
    file: null
  }
  fileList.value = []
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑视频'
  form.value = {
    videoId: row.videoId,
    title: row.title,
    content: row.content,
    file: null
  }
  fileList.value = []
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这个视频吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteVideoService(row.videoId)
      if (res.code === 1000) {
        ElMessage.success('删除成功')
        getVideoList()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

function handleFileChange(file, fileListArr) {
  form.value.file = file.raw
  fileList.value = fileListArr
}

function beforeUpload(file) {
  // 可加类型/大小校验
  return true
}

// 获取视频URL
const getVideoUrl = (video) => {
  if (!video) return '';
  const fileName = video.split('\\').pop().split('/').pop();
  return `http://localhost:1010/upload/directory/${fileName}`;
};

// 提交表单
async function handleSubmit() {
  await formRef.value.validate()
  if (!form.value.file) {
    ElMessage.error('请先选择视频文件')
    return
  }
  uploading.value = true
  try {
    const fd = new FormData()
    fd.append('file', form.value.file)
    fd.append('title', form.value.title)
    fd.append('content', form.value.content)
    
    let res
    if (form.value.videoId) {
      // 更新视频
      fd.append('videoId', form.value.videoId)
      res = await updateVideoService(fd)
    } else {
      // 上传新视频
      fd.append('courseId', courseId)
      res = await uploadVideoService(fd)
    }

    if (res.code === 1000) {
      ElMessage.success(form.value.videoId ? '更新成功' : '上传成功')
      dialogVisible.value = false
      getVideoList()
    } else {
      ElMessage.error(res.msg || (form.value.videoId ? '更新失败' : '上传失败'))
    }
  } catch (e) {
    ElMessage.error(form.value.videoId ? '更新失败' : '上传失败')
  } finally {
    uploading.value = false
  }
}

onMounted(() => {
  getVideoList()
})
</script>

<style scoped>
.video-detail {
  padding: 20px;
}
.video-list {
  margin-top: 20px;
}
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>